import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../utils/dio_util.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../tabs.dart';
import '../../widget/my_dialog.dart';

class SmsLogin extends StatefulWidget {
  @override
  _SmsLoginState createState() => _SmsLoginState();
}

class _SmsLoginState extends State<SmsLogin> {
  final smsLoginFormKey = GlobalKey<FormState>();
  TextEditingController _userPhoneController = TextEditingController(); //手机号码
  TextEditingController _codeController = TextEditingController(); //验证码
  String userName = '123456';
  String smsCode = '1234';
  bool autoValidate = false;
  bool disabledSend = true; //禁止发送验证码
  int currentTime = 0; //计时
  String sendText = '发送验证码';
  Timer timer; //倒计时的计时器
  //验证手机号
  String validatorPhone(value) {
    if (value.isEmpty) {
      return '手机号不能为空';
    }
    if (value.length != 11) {
      return '手机号长度不正确';
    }
    RegExp reg = new RegExp(r"^1\d{10}$");
    if (!reg.hasMatch(value)) {
      return '手机号格式不对';
    }
    return null;
  }




  //验证验证码
  String validatorCode(value) {
    if (value.isEmpty) {
      return '验证码不能为空';
    }

    if (value.length != 4) {
      return '验证码长度不正确';
    }

    return null;
  }

  //发送计时
  startCountDown() {
    timer = new Timer.periodic(Duration(seconds: 1), (Timer timer) {
      currentTime--;
      setState(() {
        if (currentTime == 0) {
          timer.cancel(); //倒计时结束取消定时器
          disabledSend = false; //按钮可点击
          currentTime = 60; //重置时间
          sendText = '发送验证码'; //重置按钮文本
        } else {
          sendText = '重新发送($currentTime)'; //更新文本内容
        }
      });
    });
  }

  //验证码登录
  doLogin() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    var api = '/api/mall/auth/mobile.service';
    MyDialog.loaddingDialog(context: context, title: '登陆中');
    if (smsLoginFormKey.currentState.validate()) {
      smsLoginFormKey.currentState.save();
      var http = DioUtil();
      Map<String, dynamic> param = {'smsCode': smsCode, 'userName': userName};
      http.post(api, data:param).then((res) {
        if (res['code'] == 200) {
          var result = res['result'];
          sp.setString('token', result);
          //保存用户信息
          sp.setBool('isLogin', true);
          Navigator.pop(context);
          Navigator.of(context)
              .pushReplacement(MaterialPageRoute(builder: (context) {
            return Tabs();
          }));
        } else {
          Fluttertoast.showToast(msg: res['msg']);
        }
      });
    } else {
      Navigator.pop(context);
      setState(() {
        autoValidate = true;
      });
    }
  }

  //发送验证码
  Future<dynamic> sendCode() async {
    RegExp reg = new RegExp(r"^1\d{10}$");
    if (userName.isEmpty) {
      setState(() {
        disabledSend = true;
      });
      return '手机号不能为空';
    } else if (userName.length != 11) {
      setState(() {
        disabledSend = true;
      });
      return '手机号长度不正确';
    } else if (!reg.hasMatch(userName)) {
      setState(() {
        disabledSend = true;
      });
      return '手机号格式不对';
    } else {
      setState(() {
        disabledSend = false;
      });
      var http = DioUtil();
      Map<String, dynamic> res = await http
          .get('/api/mall/auth/verifyCode/send.service', data:{'phone': userName});
      return res;
    }
  }

  @override
  Widget build(BuildContext context) {
    RegExp reg = new RegExp(r"^1\d{10}$");
    return Theme(
      data: ThemeData(
          primaryColor:Colors.red
      ),
      child: Form(
        key: smsLoginFormKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          children: [
            TextFormField(
              controller: _userPhoneController,
              validator: validatorPhone,
              autovalidate: autoValidate,
              keyboardType: TextInputType.phone,
              decoration: InputDecoration(
                  suffix: IconButton(
                    icon:Icon(Icons.close),
                    onPressed: (){
                      _userPhoneController.text = '';
                    },
                  ),
                  hintText: "请输入手机号", icon: Icon(Icons.phone_android)),
              onChanged: (value) {
                if (value.length == 11 && reg.hasMatch(value)) {
                  setState(() {
                    disabledSend = false;
                  });
                } else {
                  setState(() {
                    disabledSend = true;
                  });
                }
                this.userName = value;
              },
            ),
            SizedBox(height: 10),
            Container(
              width: 700.w,
              height: 80.h,
              child: Row(
                children: [
                  Expanded(
                    flex: 2,
                    child: TextFormField(
                      controller: _codeController,
                      validator: validatorCode,
                      autovalidate: autoValidate,
                      keyboardType: TextInputType.number,
                      decoration: InputDecoration(
                        hintText: "请输入验证码",
                        suffix: IconButton(
                          icon:Icon(Icons.close),
                          onPressed: (){
                            _codeController.text = '';
                          },
                        ),
                        icon: Icon(Icons.verified_user),
                      ),
                      onChanged: (value) {
                        // print(value);
                        this.smsCode = value;
                      },
                    ),
                  ),
                  SizedBox(
                    width: 20.w,
                  ),
                  Expanded(
                    flex: 1,
                    child: FlatButton(
                        disabledColor: Colors.grey.withOpacity(0.36),
                        color: disabledSend == true
                            ? Colors.grey[200]
                            : Colors.orangeAccent,
                        onPressed: disabledSend
                            ? null
                            : () {
                                Future<dynamic> res = sendCode();
                                res.then((res) {
                                  if (res.runtimeType == String) {
                                    Fluttertoast.showToast(msg: res);
                                  } else if ((res is Map) &&
                                      (res['code'] != 200)) {
                                    Fluttertoast.showToast(msg: res['msg']);
                                  } else {
                                    startCountDown();
                                  }
                                });
                              },
                        child: Text(
                          sendText,
                          style: TextStyle(
                              color: disabledSend ? Colors.grey : Colors.white,
                              fontSize: 25.sp),
                        )),
                  )
                ],
              ),
            ),
            SizedBox(height: 20),
            Container(
              width: 650.w,
              height: 90.h,
              child: RaisedButton(
                child: Text(
                  "登录",
                  style: TextStyle(color: Colors.white, fontSize: 35.sp),
                ),
                color: Colors.red,
                onPressed: doLogin,
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();

  }
}
